import { create } from "apisauce";
import { NavigationActions } from "react-navigation";
import AsyncStorage from "@react-native-community/async-storage";
import config from "config";

import _app from "../app";
import { getStore } from "./index";

const { server } = config;

// import NavigationService from "./navigationService";

const api = create({
  baseURL: `${server}/xxx`,
});

// const api = create({
//   baseURL: "http://47.244.154.154:8080/xxx",
// });

export const request = async (type, url, reqData, option = {}) => {
  const token = (await getStore("token")) || "none";
  // const uuid = (await getStore("uuid")) || "none";
  const headers = {
    "Content-Type": "application/json",
    Authorization: token,
    // Authorization:
    //   "94e14a98ac8e8853c827c12918184fcb739e2d3bf69b55f464cf85c5592ffd2b",
    ...(option.header || {}),
  };
  return api[type](url, reqData, {
    // return api[type](url, option.isFile ? reqData : { ...reqData, '94e14a98ac8e8853c827c12918184fcb739e2d3bf69b55f464cf85c5592ffd2b', uuid }, {
    headers,
  }).then(async response => {
    const { status, data } = response;
    if (status === 200) {
      if (data.code === 200) {
        return data.data;
      } else if (data.code === -7) {
        console.log("鉴权失败", response); // eslint-disable-line
        await AsyncStorage.multiRemove(["token", "uuid"]); // 清空token
        _app
          .getApp()
          ._store.dispatch(
            NavigationActions.navigate({ routeName: "Welcome" })
          );
      } else {
        return data;
      }
    } else {
      console.log("请求异常", response); // eslint-disable-line
    }
  });
};

export const post = (url, data) => request("post", url, data);
export const get = (url, data) => request("get", url, data);
